"use strict";

const router = require('express').Router();
const xml2json = require('basic-xml2json');
const api = require('../utils/api');

/* mp.weixin.qq.com verify. */
router.get('/', function (req, res, next) {
    let data = req.query, bodyData = req.body;

    let signature = data.signature,
        timestamp = data.timestamp,
        nonce = data.nonce,
        echostr = data.echostr || 'success',
        token = "sodexowxservices";
    console.log(data, '&&&&&&&&&&&&&&&&&');
    let locationId = data.locationId, openId = data.openId;
    if (locationId) {
        global.tool.send({
            method: 'get',
            uri: api.get('1d129515347d429e9a82f8d722f50a00').replace("{id}", locationId)
        }, function (error, response, body) {
            console.log(body, '****************');
            if (body && typeof body == 'string') {
                let tmp = body.split('_');
                if (tmp.length > 0) {
                    let ss = body.split(",");
                    //更新标签
                    global.weChatUtil.updateGroup("members/update", {
                        openid: openId,
                        to_groupid: ss[1]
                    }, function (weData) {
                        console.log(weData, '-----update the tag');
                        //更新本地用户的标签
                    });
                    if (tmp.length > 1) {
                        global.cacheData[openId] = {barCode: tmp[1], expire: new Date()};
                    }
                }
            }
        });
    }
    res.send(echostr);
});

router.post('/', function (req, res, next) {
    let data = req.query, bodyData = req.body;
    let signature = data.signature,
        timestamp = data.timestamp,
        nonce = data.nonce,
        echostr = data.echostr || 'success',
        token = "estam2016";
    console.log(bodyData);
    if (bodyData.xml) {
        let xml = bodyData.xml;
        let locationId = null, tt;
        if (xml.event == 'SCAN') {
            tt = xml.eventkey;
            if (tt && tt.length > 0)
                locationId = tt[0];
            console.log('----scan for scan location id:', locationId);
        } else if (xml.event == 'subscribe') {
            tt = xml.eventkey;
            if (tt && tt.length > 0) {
                locationId = tt[0].substring(8);
            }
            console.log('----scan for subscribe location:', locationId);
        }
        if (locationId) {

        }
    }
    res.send(echostr);
});

module.exports = router;
